package com.lulu.baselib.base;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.lulu.baselib.R;
import com.lulu.baselib.dialog.MyAlertDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: XuChang
 * Date: 2019/10/26 17:07
 * Email: 123286473@qq.com
 * Description:
 * History:
 */
public abstract class PermissionActivity extends BaseActivity {
    public final int REQUEST_CODE_PERMISISION = 233;

    public interface CallBack {
        void onSuccess();

        void onFailed();
    }

    CallBack mCallBack;
    AlertDialog dialog;
    boolean isNewRequestFlag = true;    //标志位

    /**
     * 请求权限
     *
     * @param permissions
     * @param callBack    权限成功时回调
     */
    protected void requestPermission(String[] permissions, CallBack callBack) {
        isNewRequestFlag = true;
        requestPermissionAction(permissions, callBack);
    }

    private void requestPermissionAction(String[] permissions, CallBack callBack) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] unGranted = checkPermission(permissions);
            if (unGranted.length == 0) {
                callBack.onSuccess();
                //检查权限是否都可以申请，不行的话，跳转到setting
                //第一次调用shouldShowRequestPermissionRationale都会返回false，所以一个标志位处理下
            } else if (!isNewRequestFlag && !checkRequestRationale(unGranted)) {
                if (mCallBack != null)
                    mCallBack.onFailed();
                MyAlertDialog myAlertDialog = new MyAlertDialog("请前往设置->应用->" + getString(R.string.app_name) + "->权限中打开相关权限，否则功能无法正常运行！", "确定", "取消",
                        new MyAlertDialog.CallBackAdapter() {
                            @Override
                            public void onConfirm(MyAlertDialog dialog) {
                                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                startActivity(intent);
                            }
                        });
                myAlertDialog.show(getSupportFragmentManager(),"dialog");
            } else {
                isNewRequestFlag = false;
                this.mCallBack = callBack;
                requestPermissions(permissions, REQUEST_CODE_PERMISISION);
            }
        } else {
            callBack.onSuccess();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 检查是否下列权限都可以申请
     *
     * @param unGranted
     * @return
     */
    private boolean checkRequestRationale(String[] unGranted) {
        for (String s : unGranted) {
            boolean b = ActivityCompat.shouldShowRequestPermissionRationale(this, s);
            //如果有不能申请的权限，返回false
            if (!b)
                return false;
        }
        return true;
    }


    private String[] getArray(List<String> list) {
        if (list == null || list.size() == 0) {
            return new String[0];
        } else {
            String[] arr = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                arr[i] = list.get(i);
            }
            return arr;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISISION:
                if (grantResults.length > 0) {
                    List<String> unGraned = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED)
                            unGraned.add(permissions[i]);
                    }
                    if (unGraned.size() == 0 && mCallBack != null) {
                        mCallBack.onSuccess();
                    } else {     //继续请求
                        requestPermissionAction(getArray(unGraned), mCallBack);
                    }
                }
                break;
        }
    }

    /**
     * 检查权限
     *
     * @param permissions
     * @return 未给予的权限，为空代表都给予了
     */
    private String[] checkPermission(String[] permissions) {
        if (permissions == null || permissions.length == 0)
            return null;
        List<String> unGranted = new ArrayList();
        for (String permission : permissions) {
            int i = ContextCompat.checkSelfPermission(this, permission);
            if (i != PackageManager.PERMISSION_GRANTED) {
                unGranted.add(permission);
            }
        }
        return getArray(unGranted);
    }
}
